package com.elephant.controller;

import com.elephant.dao.DepartmentDao;
import com.elephant.dao.EmployeeDao;
import com.elephant.pojo.Employee;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Collection;
import java.util.Date;

@Controller
@Api(value = "员工控制器", description = "员工相关api")
public class EmployeeController {

    //controller应该调service层，这里方便测试先直接调dao层
    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    DepartmentDao departmentDao;
    @RequestMapping("/emps")
    public String emps(Model model){
        Collection<Employee> allEmployees = employeeDao.getAllEmployees();

        model.addAttribute("emps",allEmployees);
        return "employee/list";
    }
    @ApiOperation(value = "查找",
            notes = "查找用户",
            httpMethod = "GET")
    @GetMapping("/emp")
    public String toAddEmp(Model model){

        Collection departments = departmentDao.getDepartments();

        model.addAttribute("departments",departments);

        return "employee/addEmployee";
    }


    @PostMapping("/emp")
    public String addEmp(Employee employee){
        employee.setBirthday(new Date());
        System.out.println(employee.toString());
        employeeDao.add(employee);

        return "redirect:/emps";
    }


    @GetMapping("/editEmp/{id}")
    public String toEditEmp(@PathVariable int id, Model model){
        Employee employee = employeeDao.getEmployeeById(id);
        Collection departments = departmentDao.getDepartments();
        model.addAttribute("employee",employee);
        model.addAttribute("departments",departments);

        return "employee/editEmployee";
    }


    @PostMapping("/editEmp")
    @ApiOperation(value = "编辑用户",
            notes = "需要传入用户实例",
            httpMethod = "post请求")
    public String editEmp(@ApiParam(value = "员工类")Employee employee){
        System.out.println(employee.toString());
        employeeDao.updateEmployee(employee);
        return "redirect:/emps";
    }


    @GetMapping("/deleEmp/{id}")
    public String deleEmp(@PathVariable int id, Model model){
        employeeDao.deleteEmployee(id);
        return "redirect:/emps";
    }
}
